﻿using System;
using System.IO;

namespace TlvLib.SiChuan
{
    static class Helper
    {
        public static bool IsValid(byte[] buffer)
        {
            return true;
        }

        public static PacketType GetPacketType(byte[] buffer)
        {
            var type = Configuration.EndianBitConverter.ToInt16(buffer, 0);
            if (!Enum.IsDefined(typeof(PacketType), type))
            {
                return PacketType.UnDefined;
            }

            return (PacketType)type;
        }

        public static byte[] GetBytes(string text, int length)
        {
            var stringBuf = Configuration.TextEncoding.GetBytes(text);
            if (stringBuf.Length > length)
            {
                throw new ArgumentException("text is too long to fit in destination byte array");
            }

            var buf = new byte[length];
            //用空格填充
            for (var i = 0; i < buf.Length; i++)
            {
                buf[i] = ProtocolConstant.StringEndingFlag;
            }

            Buffer.BlockCopy(stringBuf, 0, buf, 0, stringBuf.Length);
            return buf;
        }

        public static int CountUptoWhiteSpace(byte[] buffer, int startIndex, int len)
        {
            if (buffer == null) throw new ArgumentNullException("s");

            var i = 0;
            for (i = 0; i < buffer.Length && i < len; i++)
            {
                if (buffer[i+startIndex] == ProtocolConstant.StringEndingFlag)
                {
                    break;
                }
            }

            return i;
        }

        public static void WriteAllBytes(Stream stream, byte[] buffer)
        {
            stream.Write(buffer, 0, buffer.Length);
        }
    }
}
